import axios from "axios";

import {ElMessage} from "element-plus";

let instance;


let RRequest = class RRequest {
    constructor(config) {
        instance = axios.create(config);

        instance.interceptors.request.use(function (config) {
            const token = localStorage.getItem("tokenValue");
            if (token && config && config.headers) {
                config.headers.Authorization = 'Bearer ' + token;
            }
            return config;
        }, function (error) {
            return Promise.reject(error);
        });

        instance.interceptors.response.use(function (response) {
            return response.data;
        }, function (error) {
            const response = error.response;
            let result = response ? response.data : error;
            if (!result) {
                let statusText = response.statusText
                if (statusText) {
                    result = statusText;
                }
            }
            return Promise.reject(result);
        });
    }


    request(config) {
        return new Promise((resolve, reject) => {
            instance.defaults.headers['Cache-Control'] = 'no-store';
            instance.request(config).then(res => {
                if (res.hasOwnProperty("code") && res.code === 200 || res['access_token']) {
                    resolve(res);
                } else {
                    reject(res);
                }
            }, (e) => {
                if (e.hasOwnProperty("detail")) {
                    localStorage.removeItem("tokenValue");
                    localStorage.removeItem("userinfo")
                    ElMessage.error(e.detail)
                } else if (e === 'Internal Server Error') {
                    ElMessage.error({
                        message: "服务器异常",
                        duration: 300,
                    })
                }
                reject(e)
            })
        });
    }

    GET(config) {
        config.method = "GET";
        return this.request(config)
    }

    POST(config) {
        config.method = "POST";
        return this.request(config)
    }
}

const rRequest = new RRequest({
    baseURL: import.meta.env.VITE_APP_BASE_API
})

export default rRequest;



